package com.haohan.cloud.scm.common.tools.handler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.TableInfoHelper;
import com.haohan.cloud.scm.common.tools.util.ScmIncrementUtil;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author Created by zgw on 2019/5/21.
 */
@Component
@Slf4j
@AllArgsConstructor
public class CommonMeteObjectHandler implements MetaObjectHandler {

    private final ScmIncrementUtil scmIncrementUtil;

    @Override
    public void insertFill(MetaObject metaObject) {
        // 插入时 填充
        this.setFieldValByName("createDate", LocalDateTime.now(), metaObject);
        this.setFieldValByName("delFlag", CommonConstants.STATUS_NORMAL, metaObject);
        PigxUser pigxUser = SecurityUtils.getUser();
        if (null != pigxUser && null != pigxUser.getId()) {
            this.setFieldValByName("createBy", pigxUser.getId().toString(), metaObject);
            // 底层已实现多租户ID注入
        }

        // 设置主键 从缓存拿
        Class entityClass = metaObject.getOriginalObject().getClass();
        // 表需设置 主键字段
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
        if (null == tableInfo.getKeyProperty()) {
            return;
        }
        // 主键 字段为空时 设置
        Object idValue = metaObject.getValue(tableInfo.getKeyProperty());
        if (null != idValue && StrUtil.isNotEmpty(idValue.toString())) {
            return;
        }
        // salesC模块 主键类型为Integer
        if (metaObject.getGetterType(tableInfo.getKeyProperty()).equals(Integer.class)) {
            metaObject.setValue(tableInfo.getKeyProperty(), scmIncrementUtil.genIdInt(entityClass));
        } else {
            metaObject.setValue(tableInfo.getKeyProperty(), scmIncrementUtil.genId(entityClass));
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {

        this.setFieldValByName("updateDate", LocalDateTime.now(), metaObject);

        PigxUser pigxUser = SecurityUtils.getUser();
        if (null != pigxUser && null != pigxUser.getId()) {
            this.setFieldValByName("updateBy", pigxUser.getId().toString(), metaObject);
        }

    }
}
